package com.autorun.server.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 简单的WebSocket处理器
 * 
 * @author autorun
 * @version 1.0.0
 */
@Slf4j
public class SimpleWebSocketHandler extends TextWebSocketHandler {

    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.put(session.getId(), session);
        log.info("WebSocket连接建立: {}", session.getId());
        
        // 发送欢迎消息
        session.sendMessage(new TextMessage("{\"type\":\"welcome\",\"message\":\"WebSocket连接成功\"}"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到WebSocket消息: {} - {}", session.getId(), message.getPayload());
        
        // 简单回应
        session.sendMessage(new TextMessage("{\"type\":\"echo\",\"data\":\"" + message.getPayload() + "\"}"));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session.getId());
        log.info("WebSocket连接关闭: {} - {}", session.getId(), status);
    }

    /**
     * 获取在线连接数
     */
    public static int getOnlineCount() {
        return sessions.size();
    }
}